<script setup>
import _ from 'lodash';

/**
 * 去掉原本 key 中的某个前缀，例如对于 prefix = 'pagination'：
 *
 * - paginationTotal -> total
 * - onUpdate:paginationPageSize -> onUpdate:pageSize
 */
const getAttributesStartWith = (attributes, prefix) => {
  const filteredAttrs = reactive({});
  for (const key in attributes) {
    if (!Object.hasOwnProperty.call(attributes, key)) {
      continue;
    }
    let attrAction;
    let attrName;
    const keyParts = key.split(':');
    if (keyParts.length === 1) {
      attrName = key;
    } else if (keyParts.length === 2) {
      attrAction = keyParts[0];
      attrName = keyParts[1];
    } else {
      continue;
    }
    if (!attrName.startsWith(prefix)) {
      continue;
    }
    const regExpPrefix = new RegExp(`^${prefix}`);
    const formattedKey = _.compact([
      attrAction,
      _.lowerFirst(attrName.replace(regExpPrefix, '')),
    ]).join(':');
    filteredAttrs[formattedKey] = attributes[key];
  }
  return filteredAttrs;
};

const attributes = reactive(useAttrs());
const paginationPrefix = 'pagination';
const paginationAttributes = getAttributesStartWith(attributes, paginationPrefix);
// attributes 内的字段更新时，并不会触发 paginationAttributes 的自动更新，
// 需要我们使用 Object.assign 手动批量更新这些字段
watch(attributes, (newValue) => {
  Object.assign(
    paginationAttributes,
    getAttributesStartWith(newValue, paginationPrefix),
  );
});
</script>

<template>
  <div class="table-with-pagination">
    <ElTable v-bind="$attrs">
      <template v-for="(_, slotName) in $slots" v-slot:[slotName]="slotProps">
        <slot :name="slotName" v-bind="slotProps" />
      </template>
    </ElTable>
    <div class="pagination-container">
      <ElPagination v-bind="paginationAttributes" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.table-with-pagination {
  display: flex;
  flex-direction: column;
}

.pagination-container {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  width: 100%;
  margin-top: 20px;
}
</style>
